package de.slothsoft.commons.swing;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;

import javax.swing.JPanel;

public class GradientPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private Color startColor;
	private Color endColor;
	private boolean horizontal;

	public GradientPanel() {
		this(null, null, true);
	}

	public GradientPanel(Color startColor, Color endColor, boolean horizontal) {
		this.startColor = startColor == null ? Color.LIGHT_GRAY : startColor;
		this.endColor = endColor == null ? getBackground() : endColor;
		this.horizontal = horizontal;
	}

	@Override
	public void paint(Graphics g) {
		int width = this.horizontal ? getWidth() : 0;
		int height = !this.horizontal ? getHeight() : 0;

		GradientPaint paint = new GradientPaint(0, 0, this.startColor, width, height, this.endColor, true);

		// we need to cast to Graphics2D for this operation
		Graphics2D g2 = (Graphics2D) g;
		Paint oldPaint = g2.getPaint();
		g2.setPaint(paint);
		g2.fillRect(0, 0, getWidth(), getHeight());
		g2.setPaint(oldPaint);

		setOpaque(false);
		super.paint(g);
	}

	public Color getStartColor() {
		return this.startColor;
	}

	public void setStartColor(Color startColor) {
		this.startColor = startColor;
	}

	public Color getEndColor() {
		return this.endColor;
	}

	public void setEndColor(Color endColor) {
		this.endColor = endColor;
	}

	public boolean isHorizontal() {
		return this.horizontal;
	}

	public void setHorizontal(boolean horizontal) {
		this.horizontal = horizontal;
	}

}